<template>
  <div class="box">
    <TopSearch
      @searchHeader="searchHeader"
      @delsHeader="delsHeader"
      @addHeader="addHeader"
      @headerButtonDel="headerButtonDel"
      @headerButtonSearch="headerButtonSearch"
      @headerButtonSelect="headerButtonSelect"
      :control="control"
      :controlPosition="controlPosition"
      :positionName="positionName"
      :disabled="disabled"
      :delsable="delsable"
      :searchConfig="setFormConfig"
    />
    <ProTable
      class="protable"
      :data="tableData"
      :page="page"
      :column="column"
      :rowControl="rowControl"
      :elProps="elProps"
      :disabled="disabled"
      :controlWidth="controlWidth"
      @row-control-click="onRowControlClick"
      @selection-change="onSelectionChange"
      @page-change="onPageChange"
      @pageRefresh="pageRefresh"
    >
    </ProTable>

    <FouDialog
      :title="'添加/修改'"
      :width="'50%'"
      v-model:dialogValue="dialogValue"
    >
      <template #content>
        <div>
          <addEdit ref="AddEditref" :echo="echo"  :school="school"></addEdit>
        </div>
      </template>
      <template #footer>
        <div>
          <el-button @click="dialogValue = false">取消</el-button>
          <el-button type="primary" @click="confirm(buttonType)" color="#081F42"
            >確定</el-button
          >
        </div>
      </template>
    </FouDialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { elProps, options, controlWidth } from "./index.js";
import { setFormConfig } from "./formConfig";
import addEdit from "./addEdit/index.vue";
import { classroomList, addClassroom, updateClassroom,deleteClassroom,SchoolList } from "@/http/index.js";
import { dayjs } from "element-plus";
import { loading, closeLoading,messageBox,message } from "@/common/function.js";

const echo = ref({});

//搜索彈窗
const searchDiolog = ref(false);
const headerButtonSearch = () => {
  console.log('headerButtonSearch');
  searchDiolog.value = true;
};

const searchDialog = (row, type) => {
  searchDiolog.value = false;
  console.log(row, type);
};

// 添加編輯彈窗
const AddEditref = ref(null);
const confirm = (type) => {
  AddEditref.value.DialogCofirm(async (e) => {
    console.log(e);
    if (e) {
      if (type == "add") {
        if (e.id) {
          delete e.id;
        }
        await addClassroomList(e);
        dialogValue.value = false;
      }
      if (type == "edit") {
        await updateClassroomList(e);
        dialogValue.value = false;
      }
    }
  });
};
// 修改教室
const updateClassroomList = async (e) => {
  const data = await updateClassroom(e);
  if (data.code == 200) {
    tableList();
    message('修改教室成功')
  }
};
// 添加教室
const addClassroomList = async (e) => {
  console.log(e);
  const data = await addClassroom(e);
  console.log(data);
  if (data.code == 200) {
    tableList();
    message('添加教室成功')
  }else{
    message('添加教室失敗')
  }
};
// 分页数据（不给就没有分页）
const page = reactive({
  current_page: 1, //当前页
  per_page: 10, //每页条数
  total: 10, //总条数
  page_size: [10, 20, 30], //可选分页条数
});
// 字段名对应表头
const column = {
  sort: "排序",
  name: "教室名稱",
  color:"顏色",
  statuss: "狀態",
  create_time: "發佈時間",
};
// 表格顶部操作按钮
const control = ["search", "dels", "add"];
const controlPosition = [];
const positionName = ref("");

// 未选中数据是 禁用项
const disabled = ["dels"];
const delsable = ref(true);

const headerButtonDel = () => {
  console.log("headerButtonDel");
};

const headerButtonSelect = () => {
  console.log("headerButtonSelect");
};

const searchHeader = (e, type) => {
  Object.assign(obj, e);
  tableList();
};

const dialogValue = ref(false);
const buttonType = ref("");
const addHeader = async() => {
  await schoolSelect()
  buttonType.value = "add";
  echo.value = {
    name: "",
    school_id: "",
    status: "",
    sort: 0,
    color: "",
  };
  dialogValue.value = true;
};

// 表格行内操作按钮
const rowControl = ["rowedit", "rowdel"];

/**表格行内操作
 * @row {object} 行内数据
 * @type {string} 点击按钮类型
 */
const onRowControlClick = async({ scope: { row }, type }) => {
  if (type == "rowedit") {
      await schoolSelect()
    const { id, name, school_id, status, sort, color } = row;
    buttonType.value = "edit";
    dialogValue.value = true;
    echo.value = { id, name, school_id, status, sort, color};
  }
  if (type == 'rowdel') {
        messageBox().then(async () => {
        await delClassroomList(row.id) 
    })
  }
}
const delClassroomList = async (id)=>{
  const data = await deleteClassroom(id)
  if (data.code == 200) {
    tableList()
    message('成功刪除教室')
  }else{
    message('刪除教室失敗')
  }
}
/** 多选
 * @selected {Array} 被选中的行
 */
const ids = ref('')
const onSelectionChange = (e) => {
  let row_id = []
  e.forEach(e => {
    row_id.push(e.id)
  });
  ids.value = row_id.toString()
  delsable.value = e.length === 0;
};
const delsHeader = () => {
    messageBox().then(async () => {
        await delClassroomList(ids.value) 
    }).catch(e=>{})
};
/**
 * @e {number} 分页操作后的值（当前页|改变后的每页条数）
 * @type {string} <current|size> 分页操作类型（当前页改变|每页条数改变）
 */
const onPageChange =async ({ e, type }) => {
  console.log(e, type);
  if (type == "current") {
    obj.page = e
  }
  if (type == "size") {
     obj.page = 1
    obj.limit = e
  }
  await tableList()
};
// 弹窗
const dialogVisible = ref(false);

const handleClose = (done) => {
  dialogVisible.value = false;
};

const tableData = ref([])
const obj = reactive({
  school_id:localStorage.getItem('school_id'),
  page: page.current_page,
  limit: page.per_page,
  name: "",
  status: "",
  time: "",
});
const tableList = async ()=>{
  loading()
  const data = await classroomList(obj)
  if (data.code == 200) {
    data.data.data.map(e=>e.status == 1 ?  e.statuss = '正常' :    e.statuss = '禁用')
    tableData.value = data.data.data
    page.current_page = data.data.current_page
    page.per_page = data.data.per_page
    page.total = data.data.total
    console.log( tableData.value);
  }
  closeLoading()
}
const school = ref([]);
const schoolSelect = async () => {
  let fromobj = {
    page: 1,
    limit: 100,
    name: "",
    status: "",
    time: "",
  };
  const data = await SchoolList(fromobj);
  if (data.code == 200) {
    data.data.data.map((e) => {
      (e.label = e.name), (e.value = e.id);
    });
    school.value = data.data.data;
  } else {
    message("学校請求超時請稍後重試", "warning");
  }
};
const pageRefresh = async () => {
  await tableList();
};
onMounted(() => {
  tableList();
});
// const dialogForm = ref(null);
// const DialogCofirm = () => {
//   dialogForm.value.submit((e) => {
//     console.log(e);
//   });
// };
</script>

<style lang="less" scoped>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.box {
  padding: 16px 33px;
}
</style>